import {LocalStorageDB} from './db/localstorage'
import {IndexDB} from './db/indexdb'



export interface DATA {
    url: string;
    method: string;
    body: any;
    result: any;
	headers: any;
}

export interface DBFUN {
    setDB: (data: DATA | DATA[]) => void; // 设置 DB
    getDB: () => Promise<DATA[]>; // 获取 DB
    clear: () => void; // 清空
    downloadDBJson: (fn?: (data: DATA[]) => any[]) => Promise<void>; // 下载数据为 JSON
}

export class StorageDB implements DBFUN {
    key = ''
    mode = ''
    DBName = ''
    db: LocalStorageDB | IndexDB

    constructor(dbKey: string, mode: 'localStorage' | 'indexedDB', dbname: string) {
        this.key = dbKey
        this.mode = mode
        this.DBName = dbname
        switch (mode) {
            case 'localStorage':
                this.db = new LocalStorageDB(dbKey, dbname)
                break
            case 'indexedDB':
                this.db = new IndexDB(dbKey, dbname)
                break
            default:
                throw new Error(`参数'mode'(存储模式) 填写错误: ${mode}`);
        }
    }
    setDB(data: DATA | DATA[]) {
        this.db.setDB(data)
    }
    getDB() {
        return this.db.getDB()
    }
    clear() {
        this.db.clear()
    }
    downloadDBJson(fn?: (data: DATA[]) => any[]) {
        return this.db.downloadDBJson(fn)
    }
}